import { IAxiosRes } from '@/api'
// import { useAppDispatch, useAppSelector } from '@/store/hook'
// import {  refreshAction, TOKEN_KEY } from '@/store/reducers/login'
import {
  logoutAction,
  refreshAction,
  REFRESH_TOKEN_KEY,
  Token,
  TOKEN_KEY
} from '@/store/reducers/login'
import { Toast } from 'antd-mobile'
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
import { getStorage, hasStorage } from './loaclStorage'
import { history } from '@/index'
// 无感刷新函数
export const refreshAPI = (refreshToken: string): IAxiosRes<Token> => {
  return axios({
    baseURL: 'http://geek.itheima.net/v1_0/',
    url: '/authorizations',
    method: 'put',
    headers: {
      Authorization: `Bearer ${refreshToken}`,
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}
const instance = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0/',
  // baseURL: 'http://toutiao.itheima.net/v1_0/',
  timeout: 5000
})

instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (hasStorage(TOKEN_KEY)) {
      config.headers!.Authorization = `Bearer ${getStorage(TOKEN_KEY)}`
    }
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response: AxiosResponse) => {
    return response
  },
  async (error: AxiosError) => {
    console.dir(error)
    if (error.response === undefined) {
      // 没有值,为无网络状态
      Toast.show({
        icon: 'fail',
        content: '服务器异常'
      })
    } else {
      // 如果没有权限,无感刷新操作
      if (error.response.status === 401) {
        const storeModule = await import('@/store')
        // 如果有刷新token
        if (hasStorage(REFRESH_TOKEN_KEY)) {
          try {
            const refreshToken = getStorage(REFRESH_TOKEN_KEY)
            const token = getStorage(TOKEN_KEY)
            await storeModule.store.dispatch(refreshAction(refreshToken))
            return instance({
              ...error.config,
              headers: {
                ...error.config.headers,
                Authorization: `Bearer ${token}`
              }
            })
          } catch (error) {
            Toast.show('请先登录')
            storeModule.store.dispatch(logoutAction())
            history.replace('/login')
            return Promise.reject(error)
          }
        }
        // 如果没有刷新token,返回登陆页
        else if (!hasStorage(REFRESH_TOKEN_KEY)) {
          Toast.show('请先登录')
          storeModule.store.dispatch(logoutAction())
          history.replace('/login', {
            redirect: history.location.pathname
          })
          return Promise.reject(error)
        }
      }
      // 有值,为接口错误
      Toast.show({
        icon: 'fail',
        content: error.response.data.message
      })
    }
    return Promise.reject(error)
  }
)

export default instance
